<!--
 * @Author: 冯本桥
 * @Date: 2025-02-17 14:40:59
 * @LastEditTime: 2025-03-07 14:21:59
 * @LastEditors: 冯本桥
 * @Description:
 * @FilePath: \teach_system_fe\src\components\Basic\FromPage\index.vue
-->
<template>
  <div>
    <el-form
      ref="fromRef"
      :model="formDate"
      :rules="rules"
      :label-width="labelWidth"
      class="demo-ruleForm"
      :disabled="disabledFrom"
    >
      <div
        class="box"
        :style="{
          gridTemplateColumns: `repeat(${gridData.columns},1fr)`,
          gridTemplateRows: `repeat(${gridData.rows}, ${gridData.rowsWidth})`,
          gap: `${gridData.columnsNumber} ${gridData.rowsNumber}`,
        }"
      >
        <template v-for="(item, index1) in config">
          <el-form-item
            v-if="!item.show"
            :key="index1"
            :label="item.label || ''"
            :prop="item.value"
            :class="{ singleColumn: item.singleColumn }"
          >
            <el-select
              v-if="item.type === 'select'"
              v-model="formDate[item.value]"
              style="width: 100%"
              clearable
              :placeholder="item.placeholder"
              :disabled="item.disabled"
              filterable
              @change="
                $emit('selectChange', { type: item.value, value: $event })
              "
            >
              <el-option
                v-for="(i, index2) in item.option"
                :key="index2"
                :label="i.label || i.name || i.childrenName || i.realName"
                :value="i.value || i.id || i.childrenId || i.label"
              />
            </el-select>
            <el-input
              v-if="item.type === 'input'"
              v-model.trim="formDate[item.value]"
              :placeholder="item.placeholder"
              :maxlength="item.max"
              :disabled="item.disabled"
              @change="item.changes ? item.changes($event) : changes($event)"
            >
              <template v-if="item.append" slot="append">{{
                item.append
              }}</template>
            </el-input>
            <el-input-number
              v-else-if="item.type === 'inputNumber'"
              v-model="formDate[item.value]"
              :min="item.min || 1"
              :max="item.max"
              :placeholder="item.placeholder"
              :disabled="item.disabled"
              :style="{'width': item.width?item.width:'100%'}"
            />
            <el-cascader
              v-else-if="item.type === 'cascader'"
              v-model="formDate[item.value]"
              style="width: 100%"
              :placeholder="item.placeholder"
              :options="item.options"
              filterable
            />
            <el-date-picker
              v-else-if="item.type === 'picker'"
              v-model="formDate[item.value]"
              style="width: 100%"
              type="date"
              :picker-options="item.pickerOptions || {}"
              :value-format="item.valueFormat || 'yyyy-MM-dd'"
              :placeholder="item.placeholder"
            />
            <el-date-picker
              v-else-if="item.type === 'morePicker'"
              v-model="formDate[item.value]"
              style="width: 100%"
              type="datetimerange"
              :value-format="item.valueFormat"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <el-input
              v-else-if="item.type === 'textarea'"
              v-model="formDate[item.value]"
              :autosize="{ minRows: 3, maxRows: 4 }"
              type="textarea"
              :placeholder="item.placeholder"
            />
            <el-radio-group
              v-else-if="item.type === 'radio'"
              v-model="formDate[item.value]"
            >
              <el-radio
                v-for="(j, index3) in item.option"
                :key="index3"
                :label="j.value"
              >{{ j.label }}</el-radio>
            </el-radio-group>
            <el-rate
              v-else-if="item.type === 'rate'"
              v-model="formDate[item.value]"
              style="margin-top: 8px"
              @change="item.changes ? item.changes($event) : changes($event)"
            />
            <template v-else-if="item.type === 'upload'">
              <el-upload
                v-if="item.listType"
                :ref="item.value"
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(
                      response,
                      file,
                      fileList,
                      item.value,
                      item.listType
                    )
                "
                :action="item.action || action"
                list-type="picture-card"
                :on-remove="handleRemove"
                :file-list="
                  formDate[item.value]
                    ? JSON.parse(JSON.stringify(formDate[item.value]))
                    : []
                "
              >
                <i class="el-icon-plus" />
              </el-upload>
              <el-upload
                v-else
                class="avatar-uploader"
                :action="item.action || action"
                :show-file-list="false"
                :on-preview="handlePictureCardPreview"
                :on-remove="
                  (file, fileList) => handleRemove(file, fileList, item.value)
                "
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(response, file, fileList, item.value)
                "
              >
                <template v-if="disabledFrom">
                  <el-image
                    v-if="formDate[item.value]"
                    class="avatar"
                    :src="formDate[item.value]"
                    :preview-src-list="[formDate[item.value]]"
                    fit="fit"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </template>
                <template v-else>
                  <img
                    v-if="formDate[item.value]"
                    :src="formDate[item.value]"
                    class="avatar"
                  >
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </template>
              </el-upload>
            </template>
            <v-distpicker
              v-if="item.type === 'distpicker' && !disabledFrom"
              :province="formDate.province"
              :city="formDate.city"
              :area="formDate.area"
              style="margin-top: 40px; text-align: left"
              @change="distpickerChange($event, item.value)"
            />
            <div
              v-if="item.type === 'babyName'"
              v-loading="item.loading"
              class="babyName"
              :class="{ 'disabled-div': item.disabled }"
            >
              <template v-if="item.option && item.option.length > 0">
                <div
                  v-for="(it, idx) in item.option"
                  :key="idx"
                  class="babyNameItem"
                  @click="select(idx, index1, item.value)"
                >
                  <img v-if="it['select']" src="@/assets/select.png">
                  <div v-else />
                  <span>{{ it.childrenName }}</span>
                </div>
              </template>
              <span v-else>暂无宝宝信息</span>
            </div>
          </el-form-item>
        </template>
        <slot />
      </div>
    </el-form>
    <slot name="append" />
    <div v-if="butShow" class="footer-btn">
      <el-button
        class="footer-item"
        type="primary"
        :disabled="disabledFrom"
        @click="submitForm"
      >{{ btnText }}</el-button>

      <el-button
        v-if="reset"
        class="footer-item"
        @click="resetFields"
      >重置</el-button>
    </div>
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker'
export default {
  components: { VDistpicker },
  props: {
    // 默认值
    value: {
      type: Object,
      default: () => {}
    },
    rules: {
      type: Object,
      default: () => {}
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    fromConfig: {
      type: Array,
      default: () => []
    },
    btnText: {
      type: String,
      default: '确定'
    },
    reset: {
      type: Boolean,
      default: false
    },
    butShow: {
      type: Boolean,
      default: true
    },
    disabledFrom: {
      type: Boolean,
      default: false
    },
    gridData: {
      type: Object,
      default: () => ({
        columns: 1, // 默认列数
        rows: 1, // 默认行数
        rowsWidth: '77px',
        columnsNumber: '10px',
        rowsNumber: '10px'
      })
    }
  },
  data () {
    return {
      config: [],
      formDate: {
        province: '',
        city: '',
        area: ''
      },
      action: '/api/system/upload'
    }
  },
  computed: {},
  watch: {
    fromConfig: {
      immediate: true,
      handler: function (newValue, oldValue) {
        this.config = newValue
      },
      deep: true // 启用深度监听
    },
    value: {
      immediate: true,
      handler: function (newValue, oldValue) {
        console.log('value>>>>>', this.value)
        for (const key in newValue) {
          this.$set(this.formDate, key, newValue[key])
        }
        console.log(this.formDate, 56756)
      },
      deep: true // 启用深度监听
    }
  },
  created () {
    for (const key in this.value) {
      this.$set(this.formDate, key, this.value[key])
    }
  },
  mounted () {},
  methods: {
    select (i, i2, k) {
      this.$set(
        this.config[i2]['option'][i],
        'select',
        !this.config[i2]['option'][i]['select']
      )
      this.$set(this.formDate, k, this.config[i2]['option'])
      this.$refs.fromRef.validateField(k)
    },
    distpickerChange (e, k) {
      for (const key in e) {
        this.formDate[key] = e[key].value
      }
      this.formDate[k] = e
    },
    submitForm () {
      return new Promise((resolve, reject) => {
        return this.$refs.fromRef.validate((valid) => {
          if (valid) {
            console.log('显示》》', this.formDate)
            this.$emit('submitForm', this.formDate)
            resolve(this.formDate)
          }
        })
      })
    },
    changes () {},
    resetFields () {
      this.$refs.fromRef.resetFields()
      this.formDate = {
        province: '',
        city: '',
        area: ''
      }
      for (let i = 0; i < this.config.length; i++) {
        if (this.config[i]['type'] === 'babyName') {
          this.config[i]['option'] = []
        }
      }
    },
    handleAvatarSuccess (response, file, fileList, value, listType) {
      // console.log(response, file, fileList, value, listType);
      console.log(value, listType)

      if (listType && response) {
        this.formDate[value] = Array.isArray(this.formDate[value])
          ? this.formDate[value]
          : []
        this.formDate[value].push(response.data.url)
      } else {
        this.$set(this.formDate, value, response.data.url)
      }
    },

    handleRemove (file, fileList, value) {
      this.dialogImageUrl = ''
      this.$set(this.formDate, value, '')
    },

    handlePictureCardPreview (file) {
      console.log(file)

      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
.demo-ruleForm {
  ::v-deep.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }

  ::v-deep.box {
    display: grid;

    .el-form-item__label {
      font-weight: bold;
    }

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.footer-btn {
  margin: 0 -30px;
  margin-top: 30px;
  padding: 15px 0;
  border-top: 1px solid #eeeeee;

  .footer-item {
    margin-left: 30px;
  }
}

.singleColumn {
  grid-column: 1 / -1;
}

.babyName {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-row-gap: 24px;
  position: relative;
  border-radius: 4px;
  border: 1px solid #ebebee;
  padding: 24px;

  .babyNameItem {
    display: flex;
    align-items: center;

    div {
      width: 16px;
      height: 16px;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 3px;
      border: 1px solid #dcdcdc;
      margin-right: 8px;
    }

    img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }

    span {
      font-family: Source Han Sans SC, Source Han Sans SC;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.9);
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
  }
}
.disabled-div {
  pointer-events: none; /* 用户无法通过鼠标点击选择 */
  cursor: not-allowed; /* 显示不允许的鼠标图标 */
  background-color: #f5f7fa;
  border-color: #dfe4ed;
  div {
    opacity: 0.6;
  }
}
</style>
